from datetime import timedelta

from flask import Blueprint, request, jsonify, render_template, current_app, make_response, session, redirect
from flask_jwt_extended import create_access_token
from models import db, User

api_bp = Blueprint('auth', __name__)


# 注册路由
@api_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')

    try:
        data = request.get_json()
        if not data:
            return jsonify({"message": "请输入注册信息"}), 400

        required_fields = ['username', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({"message": f"{field} 是必填项"}), 400

        if User.query.filter_by(username=data['username']).first():
            return jsonify({"message": "用户名已存在"}), 400

        user = User(username=data['username'])
        user.set_password(data['password'])

        db.session.add(user)
        db.session.commit()

        return jsonify({"message": "注册成功"}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({"message": f"注册失败: {str(e)}"}), 500


# 登录路由
@api_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    try:
        data = request.get_json()
        if not data:
            return jsonify({"message": "请输入账号密码"}), 400

        user = User.query.filter_by(username=data.get('username')).first()

        if not user or not user.verify_password(data.get('password')):
            return jsonify({"message": "账号密码错误"}), 401

        access_token = create_access_token(
            identity=str(user.id),
            expires_delta=current_app.config['JWT_ACCESS_TOKEN_EXPIRES']
        )

        response = make_response(jsonify({
            "message": "登录成功",
            "user": {
                "username": user.username
            }
        }))

        # 将token存入session
        session['token'] = access_token
        # 设置session的有效期（可选）
        session.permanent = True
        current_app.permanent_session_lifetime = timedelta(hours=24)

        remember_me = data.get('rememberMe', False)
        if remember_me:
            response.set_cookie('username', user.username, max_age=3600 * 24 * 7)
            # 警告：生产环境禁止存储明文密码！
            response.set_cookie('password', data.get('password'), max_age=3600 * 24 * 7)

        return response

    except Exception as e:
        current_app.logger.error(f'登录异常: {str(e)}')
        return jsonify({"message": f"登录失败: {str(e)}"}), 500

#退出登录路由
@api_bp.route('/logout')
def logout():
    session.pop('token', None)
    return redirect('/login')